package com.cloud.poetry.base.config;

import com.cloud.poetry.base.databases.DynamicDataSource;
import com.cloud.poetry.core.constant.DataSourceEnum;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mengxj
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.first")
    public DataSource firstDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.second")
    public DataSource secondDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<Object, Object> dataSources = new HashMap<>(2);
        dataSources.put(DataSourceEnum.FIRST, firstDataSource);
        dataSources.put(DataSourceEnum.SECOND, secondDataSource);
        return new DynamicDataSource(firstDataSource, dataSources);
    }
}
